package cn.qayy.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.CollectionConstant;
import cn.qayy.constants.Constant;
import cn.qayy.dto.CargoInvoiceApplyDTO;
import cn.qayy.dto.CargoInvoiceApplyDownMB;
import cn.qayy.dto.CostDTO;
import cn.qayy.dto.Msg;
import cn.qayy.dto.MsgInfo;
import cn.qayy.dto.RegisterDTO;
import cn.qayy.po.CargoInvoiceApply;
import cn.qayy.po.CostP;
import cn.qayy.po.Register;
import cn.qayy.service.ICostService;
import cn.qayy.service.IRegisterService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.DateUtils;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ExcelUtils;
import cn.qayy.utils.JsonUtil;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;
import cn.qayy.utils.UploadHandler;

/**
 * 费用管理 controller
 */
@SuppressWarnings("all")
@Controller
@RequestMapping(value = "/cost/")
public class CostController {
	
	@Resource(name = "costServiceImpl")
	private ICostService costService = null;
    @Resource(name = "registerServiceImpl")
    private IRegisterService registerService = null;
	
	/**
	 * 新增、更新
	 * @param cost
	 * @param flag
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "costUiAU")
	public Object saveOrUpdate(CostP cost,String flag, HttpServletRequest request) {
		Msg msg = null;
		try {
			/***
			 * 获取项目上下文的共享数据
			 */
			cost.setDataer(request.getSession().getAttribute("username")+"");
			String[] typeSplit = cost.getCostType().split("-");
			if(typeSplit.length>1) {
				cost.setCostType(typeSplit[0]+"费用");
				cost.setCostTypeTwo(typeSplit[1]);
			}
			
			Map<String, Object> params = new HashMap<>();
			List<String> cnames = new ArrayList<>();
			cnames.add(cost.getTerminal());
			params.put("cname", cnames);
			List<Register> list = registerService.selectByMap(params);
			String terminal = cost.getTerminal();
			if(list!=null && list.size()>0) {
				terminal = list.get(0).getZhengheqs();
			}
			cost.setTerminal(terminal);
			
			if (flag.equals("N")) { // N:新增
				costService.insert(cost);
			} else if (flag.equals("E")) {// E:修改
				costService.update(cost);
			}
			
			msg = new Msg(Constant.SUCESSFUL_CODE, cost);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/**
	 * 根据id查询
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectByID")
	public Object selectByID(Integer id,HttpServletRequest request) {
		Msg msg = null;
		try {
			CostP cargo = costService.selectByID(id);
			msg = new Msg(Constant.SUCESSFUL_CODE,cargo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/**
	 * 根据查询条件，查询结果列表
	 * @param dto
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "selectForList")
	public Object selectForList(CostDTO dto,HttpServletRequest request) {
		Msg msg = null;
		try {
			PageInfo<CostP> pageInfo = costService.selectForList(dto);
			
			msg = new Msg(Constant.SUCESSFUL_CODE, pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE, Constant.FAIL_MSG+e.getMessage());
		}
		return msg;
	}
	
	/***
	 * 页面下载已筛选的记录
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		try {
			List<CostDTO> loadDataList = DownLoadUtil.getInstance().getTargetDownLoadDataList(CostDTO.class);
			String downloadPath = ExcelUtils.getInstance().dataToExcelDxls("费用申请",StringUtil.listToStrArray(CollectionConstant.cost_mb),loadDataList);
			String url = request.getContextPath()+"/servlet/FileDownServlet?url="+downloadPath;
			response.sendRedirect(url);
		} catch (Exception e) {
			e.printStackTrace();
		}  
	}
	
	@ResponseBody
    @RequestMapping(value="daoru")
    public String uploadCostList(@RequestParam("excelFile") MultipartFile file,HttpServletRequest request){
    	String resultList ="";
    	Msg msg = null;
    	int listSize = 0;	//excel记录数
    	int doSize = 0;	//执行成功记录数
    	try {
			Map<String, List<Uploadable>> map = UploadHandler.getLastData(file,CostDTO.class);
			/**用户上传的总记录数**/
			MsgInfo msgInfo = (MsgInfo)map.get("totalCount").get(0);
			listSize = StringUtil.parseInt(msgInfo.getErr_num());
			if(map.get("fail") != null && !map.get("fail").isEmpty()) {//前台提示消息
				//验证不通过，前台提示消息 
				List<Uploadable> list = map.get("fail");
				msg = new Msg(Constant.CHECK_CODE,list);
				resultList = JSONObject.toJSONString(msg);
			} else {//DB持久化
				//是否操作成功
				boolean isSucessful = false;
				
				List<Uploadable> listE = map.get("E");
				if(listE!=null && !listE.isEmpty()) {
					// 待更新的实体list
					List<CostP> list = new ArrayList<CostP>(listE.size()+1);
					for (Uploadable u : listE) {
						CostDTO dto = (CostDTO)u;
						
						// 封装数据
						CostP cost = null;
						cost = costService.selectByID(StringUtil.parseInt(dto.getId()));
						if(cost != null) {
							List<CostP> plist = new ArrayList<CostP>();
							plist.add(cost);
							cost.setByDTO(dto);
							//r.setToday(DateUtils.dateToString(new Date(),"yyyy/MM/dd HH:mm:ss"));
							cost.setDataer(request.getSession().getAttribute("username").toString());
							list.add(cost);
						}
					}
					if(!list.isEmpty()) {
						doSize = doSize +costService.updateByList(list);
						isSucessful = true;
					}
				}
				List<Uploadable> listN = map.get("N");
				if(listN!=null && !listN.isEmpty()) {
					//待新增的实体list
					List<CostP> list = new ArrayList<CostP>(listN.size()+1);
					for (Uploadable u : listN) {
						CostDTO dto = (CostDTO)u;
						
						//封装数据
						CostP cost = new CostP();
						cost.setByDTO(dto);
						//r.setToday(DateUtils.dateToString(new Date(),"yyyy/MM/dd HH:mm:ss"));
						cost.setDataer(request.getSession().getAttribute("username").toString());
						list.add(cost);
					}
					if(!list.isEmpty()) {
						doSize = doSize +costService.insertByList(list);
						isSucessful = true;
					}
				}
				if(isSucessful) {
					// 正常操作前台提示消息 
					msg = new Msg(Constant.SUCESSFUL_CODE,"总记录数："+listSize+"，总成功数："+listSize+"，请核查！");
					resultList = JSONObject.toJSONString(msg);
				} else {
					throw new Exception();
				}
			}
		} catch (Exception e) {
			// 异常后的前台提示消息
			e.printStackTrace();
			msg = new Msg(Constant.FAIL_CODE,Constant.FAIL_MSG+e.getMessage());
			resultList = JsonUtil.object2json(msg);
		}
		return resultList;
    }
	/***
	 * 展示UI页面
	 * @return
	 */
	@RequestMapping(value="ui.do")
	public ModelAndView ui(HttpServletRequest req) {
		ServletContext context = req.getSession().getServletContext();
		
		ModelAndView model = new ModelAndView();
		model.setViewName("cost_search_pc");
		//获取流向表的客户
		model.addObject("clientList", JSONObject.toJSONString(context.getAttribute("clientList")));
		model.addObject("provinceList", JSONObject.toJSONString(context.getAttribute("provinces")));
		model.addObject("costStatus",CollectionConstant.spStatus);
		return model;
	}
	
}
